package jdbc;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class jdbc_test2 {
    public static void main(String[] args) {
        //登录
        Map<String, String> userLoginInfo = initUI();
        //判断密码
        boolean flag = login(userLoginInfo);
    }

    private static boolean login(Map<String, String> userLoginInfo)  {
        //写JDBC代码
        Connection conn = null;
        //Statement stmt = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        //jdbc:mysql://localhost:3306/test1
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/text1","root","314159");
            String sql = "select * from user where name = ? and password = ?";
            //问号表示占位符  进行欲编译
            ps = conn.prepareStatement(sql);
            //填充占位符
            ps.setString(1,"jack");
            ps.setString(2,"123");
            rs = ps.executeQuery();
            if(rs.next()){
                return true;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }   finally {
            if(rs!=null){
                try{
                    rs.close();
                } catch(Exception e){
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try{
                    ps.close();
                } catch(Exception e){
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try{
                    conn.close();
                } catch(Exception e){
                    e.printStackTrace();
                }

            }
        }
        return false;
    }

    private static Map<String, String> initUI() {
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
        String password = sc.nextLine();
        Map<String, String> map = new HashMap<>();
        map.put("name", name);
        map.put("password",password);
        return map;
    }
}
